package com.lyc.kotlin.wanandroid.base

import android.content.Context
import android.content.IntentFilter
import android.graphics.PixelFormat
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.*
import com.lyc.kotlin.wanandroid.R
import com.lyc.kotlin.wanandroid.constant.Constant
import com.lyc.kotlin.wanandroid.event.NetworkChangeEvent
import com.lyc.kotlin.wanandroid.receiver.NetworkChangeReceiver
import com.lyc.kotlin.wanandroid.utils.CommonUtil
import com.lyc.kotlin.wanandroid.utils.KeyBoardUtil
import com.lyc.kotlin.wanandroid.utils.Preference

import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 描述
 *liuyucheng
 * Created By 刘育成 on 2019/7/30.
 */
abstract class BaseActivity : AppCompatActivity() {
    /**
     * 网络状态变化的广播
     */
    protected var mNetworkChangeReceiver: NetworkChangeReceiver? = null

    /**
     * 缓存上一次的网络状态
     */
    protected var hasNetwork: Boolean by Preference(Constant.HAS_NETWORK_KEY, true)

    /**
     * 提示View
     */
    protected lateinit var mTipView: View
    protected lateinit var mWindowManager: WindowManager
    protected lateinit var mLayoutParams: WindowManager.LayoutParams

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
        setContentView(attachLayoutRes())
        if (useEventBus()){
            EventBus.getDefault().register(this)
        }
        initData()
        initTopView()
        initView()
        start()
        initListener()
    }

    /**
     * 动态注册网络变化广播
     */
    override fun onResume() {
        super.onResume()
        val filter = IntentFilter()
        filter.addAction("android.net.conn.NETWORK_CHANGE")
        mNetworkChangeReceiver = NetworkChangeReceiver()
        registerReceiver(mNetworkChangeReceiver,filter)

    }

    private fun initListener() {

    }

    /**
     * 开始请求
     */
    abstract fun start()

    /**
     * 初始化 View
     */
    abstract fun initView()


    /**
     * 初始化 TipView
     */
    private fun initTopView() {
        mTipView=layoutInflater.inflate(R.layout.layout_network_top,null)
        mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mLayoutParams = WindowManager.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT)
        mLayoutParams.gravity = Gravity.TOP
        mLayoutParams.x = 0
        mLayoutParams.y = 0
        mLayoutParams.windowAnimations = R.style.anim_float_view // add animations
    }

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 是否使用 EventBus
     */
    abstract fun useEventBus(): Boolean

    /**
     * 布局文件id
     */
    abstract fun attachLayoutRes(): Int

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetworkChangeEvent(event: NetworkChangeEvent) {
        hasNetwork = event.isConnected
        checkNetwork(event.isConnected)
    }

    private fun checkNetwork(isConnected: Boolean) {
        if (enableNetwork()){
            if (isConnected){
                doReConnected()
                if (mTipView!=null&&mTipView.parent!=null){
                    mWindowManager.removeView(mTipView)
                }else{
                    if (mTipView.parent == null) {
                        mWindowManager.addView(mTipView, mLayoutParams)
                    }
                }
            }
        }
    }

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        start()
    }

    open fun enableNetwork(): Boolean=true

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            // 如果不是落在EditText区域，则需要关闭输入法
            if (KeyBoardUtil.isHideKeyboard(v, ev)) {
                KeyBoardUtil.hideKeyBoard(this, v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onPause() {
        if (mNetworkChangeReceiver != null) {
            unregisterReceiver(mNetworkChangeReceiver)
            mNetworkChangeReceiver = null
        }
        super.onPause()
    }




    override fun onBackPressed() {
        super.onBackPressed()
        // Fragment 逐个出栈
        val count = supportFragmentManager.backStackEntryCount
        if (count == 0) {
            super.onBackPressed()
        } else {
            supportFragmentManager.popBackStack()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus()){
            EventBus.getDefault().unregister(this)
        }
        CommonUtil.fixInputMethodManagerLeak(this)
    }
}


